import React, { useEffect, useMemo, useState } from "react";
import { pqsprojTableData_query_page } from "src/api/pqsstartWkInfo";
import { NavBar, List, Skeleton, Empty, Button, Dialog, Tabs } from "antd-mobile";
import BetterScroll from "pages/components/betterScroll";
import { API_URL, PDF_URL, FILE_VIEW, FILE_VIEW_ONLINE } from "src/config";
import { PreviewPdf, isNormalBrowser } from "src/utils/index";
import axios from "src/api/index";
import Cookies from "js-cookie";
import "./index.scss";
import { locationShape, historyShape } from "src/propType";
import Toast from "src/pages/components/clickableToast";

export function formatFileSize(size) {
    const units = ["B", "KB", "MB", "GB", "TB"];
    let idx = 0;
    while (size >= 1024 && idx < units.length - 1) {
        size /= 1024;
        idx++;
    }
    return size.toFixed(2) + " " + units[idx];
}

const FileInfo = props => {
    const [loading, setLoading] = useState(true);
    const [fileList, setFileList] = useState([]);
    const [activityKey, setactivityKey] = useState(0);

    const getList = () => {
        const kid = props.location.search?.split("?")[1];
        if (!kid) return;
        pqsprojTableData_query_page(kid).then(res => {
            const { code, data } = res;
            if (code === 200) {
                setFileList(data);
                setactivityKey(0);
                setLoading(false);
            }
        });
    };

    const toViewPdf = async record => {
        const isView = await Dialog.confirm({ content: "是否查看文件?" });
        if (!isView) return;

        if (record.svrFullPath) {
            Toast.show({
                icon: "loading",
                content: "",
                duration: FILE_VIEW_ONLINE ? 2000 : 0,
            });

            const url = (PDF_URL + record.svrFullPath).replace(/\\/g, "/");
            // if (!isNormalBrowser()) {
            //     const url = `${API_URL}/wpfile/download?dbName=GPMSPQS&kid=${record.kid}&ext=${record.ext}`;
            //     PreviewPdf(url);
            //     return;
            // }

            if (FILE_VIEW_ONLINE) {
                // 在线预览方式
                // let viewUrl = `${url}&fullfilename=${record.kid}${record.ext}&isApp=1`;
                PreviewPdf(record.svrFullPath);
            } else {
                //  downLoad 下载方式
                axios({
                    method: "GET",
                    customError: true,
                    _ingore: true,
                    url: FILE_VIEW,
                    params: {
                        fileName: `${record.kid}${record.ext}`,
                        cookies: `CRBIMSSOJWT=${Cookies.get("CRBIMSSOJWT")}`,
                        url,
                        isApp: 1,
                    },
                }).then(res => {
                    if (res.msg === "SUCCESS") {
                        Toast.show({
                            icon: "success",
                            content: "",
                        });
                        res.data && window.open(res.data);
                    } else {
                        Toast.show({
                            icon: "fail",
                            content: res.msg,
                        });
                    }
                });
            }
        } else {
            Toast.show({
                icon: "fail",
                content: "附件不存在!",
                afterClose: () => {},
            });
            return;
        }
    };

    useEffect(() => {
        getList();
    }, []);

    const hasData = fileList?.length;

    const changeTab = activityKey => {
        setactivityKey(activityKey);
    };

    const currentTabFile = useMemo(() => {
        return fileList[activityKey];
    }, [activityKey, fileList]);

    return (
        <div className="common-list">
            <NavBar back="返回" onBack={() => props.history.go(-1)}>
                附件
            </NavBar>
            <Tabs
                activeKey={activityKey}
                onChange={changeTab}
                style={{
                    "--title-font-size": "14px",
                }}
            >
                {fileList.map((tab, i) => (
                    <Tabs.Tab title={tab.dataName || "附件"} key={i} />
                ))}
            </Tabs>
            <div className="scroll-container">
                <BetterScroll ref={scroll}>
                    <div className={`${hasData ? "file-info-container" : "empty"}`}>
                        {loading ? (
                            <Skeleton.Paragraph lineCount={10} animated />
                        ) : hasData ? (
                            currentTabFile?.fileData?.map(table => {
                                const { kid, title, length, ext, addDate, userName } = table;
                                const len = formatFileSize(length);
                                return (
                                    <div className="list-container" key={kid}>
                                        <List.Item
                                            arrowIcon={false}
                                            clickable={false}
                                            onClick={e => {}}
                                        >
                                            <div className="content">
                                                <p>
                                                    <span>文件名：</span>
                                                    <span>{title}</span>
                                                </p>
                                                <p>
                                                    <span>文件大小:</span>
                                                    <span>{len}</span>
                                                </p>
                                                {/* <p>
                                                    <span>格式：</span>
                                                    <span>{ext}</span>
                                                </p> */}
                                                <p>
                                                    <span>上传日期：</span>
                                                    <span>{addDate}</span>
                                                </p>
                                                <p>
                                                    <span>上传人：</span>
                                                    <span>{userName}</span>
                                                </p>
                                            </div>
                                            <div className="btns">
                                                <Button
                                                    size="small"
                                                    color="primary"
                                                    fill="solid"
                                                    onClick={() => toViewPdf(table)}
                                                >
                                                    查看
                                                </Button>
                                            </div>
                                        </List.Item>
                                    </div>
                                );
                            })
                        ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}
                    </div>
                </BetterScroll>
            </div>
        </div>
    );
};

FileInfo.propTypes = {
    history: historyShape,
    location: locationShape,
};

export default FileInfo;
